package cn.net.xyan.kotlin

import com.github.stuxuhai.jpinyin.PinyinFormat
import com.github.stuxuhai.jpinyin.PinyinHelper

import org.junit.Assert
import org.junit.Test
import java.util.*
import java.util.regex.Pattern

/**
 * Created by zarra on 2017/5/4.
 */

class TextTest{
    val ChineseCharBegin: Char = 0x4e00.toChar()
    val ChineseCharEnd: Char = 0x9FFF.toChar()

    data class Question(val pinyin:String):Comparable<Question>{
        override fun compareTo(other: Question): Int {
            val s1 = if(list.size>=4) 6 else 3
            val s2 =  if(other.list.size>=4) 6 else 3

            var r = s1.compareTo(s2)

            if (r != 0)
                return r

            val a1 =  if (answer.length >1)  2 else 1
            val a2 =  if (other.answer.length >1)  2 else 1

            r = a1.compareTo(a2)

            if (r != 0)
                return r

            else
                return pinyin.compareTo(other.pinyin)
        }

        var list:MutableList<String> = LinkedList()
        var answer:String = ""
    }

    @Test
    fun test1(){
        val input = javaClass.classLoader.getResourceAsStream("a.txt")
        var result:MutableList<Question> = LinkedList()
        Assert.assertNotNull(input)
        val pattern = "^(\\d+)\\.?(.+)"
        val answerPattern = "^正确答案：([A-Z]+)"
        val r = Pattern.compile(pattern)
        var ar = Pattern.compile(answerPattern)
        input.use {
            val lines = input.reader().readLines()
            var q:Question? = null
            lines.forEach {
                val m = r.matcher(it)
                if(m.find()){
                    var string = m.group(m.groupCount())
                    string = string.filter {
                        it in (ChineseCharBegin + 1)..(ChineseCharEnd - 1)
                    }
                    val pinyin = PinyinHelper.convertToPinyinString(string, "", PinyinFormat.WITHOUT_TONE)

                    q = Question(pinyin)

                    result.add(q!!)

                    var first = pinyin.first()
                    first = first.toUpperCase()
                    var head = "$first $it"

                    q!!.list.add(head)
                }else{
                    if (q != null) {
                        q!!.list.add(it)
                        val rm = ar.matcher(it)
                        if (rm.find()) {
                            var string = rm.group(m.groupCount() - 1)
                            q!!.answer = string
                            q = null
                        }
                    }
                }
            }
        }

        result.sort()

        result.forEach {

            it.list.forEach {
                println(it)
            }
            //println(it.answer)
        }
    }
}